package com.wxtl.dao;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Repository;

import com.wxtl.dao.base.HibernateBaseDao;
import com.wxtl.entity.Customer;
import com.wxtl.util.DataGridModel;
import com.wxtl.util.Page;


/**
 * 
 * @author hc24
 * @modify by liulin 增加客户查询DAO
 */
@Repository
public class CustomerDAO extends HibernateBaseDao {
	private static final Log log = LogFactory.getLog(CustomerDAO.class);

	public Customer queryByCustsn(String custsn){
		List<Customer> list=getSession().createQuery("from Customer c where c.custsn=?").setString(0, custsn).list();
		if(list.size()>0)
			return list.get(0);
		return null;
	}
	
	/**
	 * 按照企业名称查询，按道理来说企业名称应该是唯一的
	 * @param entName
	 * @return
	 */
	public Customer queryByEntname(String entName){
		List<Customer> list=getSession().createQuery("from Customer c where c.entName=?").setString(0, entName).list();
		if(list.size()>0)
			return list.get(0);
		return null;
	}
	
	public Customer queryByDog(String dogSn){
		List<Customer> list=getSession().createQuery("from Customer c where c.dogsn=?").setString(0, dogSn).list();
		if(list.size()>0)
			return list.get(0);
		return null;
	}
	
	/**
	 * 统计注册总数
	 * @return
	 */
	public int getCount(){
		List<Customer> list=getSession().createQuery("from Customer c").list();
		if(list.size()>0)
			return list.size();
		return 0;
	}
	
	/**
	 * 根据customer对象查询
	 * @param dgm
	 * @param agent
	 * @return
	 */
	public Page query(DataGridModel dgm,Customer customer){
		//构建hql
		StringBuilder hql=new StringBuilder();
		List<Object> params=new ArrayList<Object>();
		hql.append("from Customer c where 1=1");
		if(customer.getAuthsn()!=null&&!"".equals(customer.getAuthsn())){
			params.add("%"+customer.getAuthsn()+"%");
			hql.append(" and c.agentsn like ?");
		}
		if(customer.getEntName()!=null&&!"".equals(customer.getEntName())){
			params.add("%"+customer.getEntName()+"%");
			hql.append(" and c.entName like ?");
		}
		if(customer.getProvince()!=null&&!"".equals(customer.getProvince())){
			params.add("%"+customer.getProvince()+"%");
			hql.append(" and c.province like ?");
		}
		if(customer.getCity()!=null&&!"".equals(customer.getCity())){
			params.add("%"+customer.getCity()+"%");
			hql.append(" and c.city like ?");
		}
		if(customer.getTel()!=null&&!"".equals(customer.getTel())){
			params.add(customer.getTel());
			hql.append(" and c.tel=?");
		}
		if(customer.getLinkman()!=null&&!"".equals(customer.getLinkman())){
			params.add("%"+customer.getLinkman()+"%");
			hql.append(" and c.linkman like ?");
		}
		if(customer.getState() !=null && customer.getState() != -1){
			params.add(customer.getState());
			hql.append(" and c.state=?");
		}
		
		hql.append(" order by c.authsn");
		return super.queryForList(hql.toString(), params.toArray(new Object[]{}), dgm.getPage(), dgm.getRows());
	}
}